package cn.wyl.user.service.impl;

import cn.wyl.basic.constant.WxConstants;
import cn.wyl.basic.dto.LoginDto;
import cn.wyl.basic.exception.BusinessException;
import cn.wyl.basic.jwt.JwtUtils;
import cn.wyl.basic.jwt.LoginData;
import cn.wyl.basic.jwt.RsaUtils;
import cn.wyl.basic.util.AjaxResult;
import cn.wyl.basic.util.HttpUtil;
import cn.wyl.basic.util.Md5Utils;
import cn.wyl.basic.util.StrUtils;
import cn.wyl.org.mapper.EmployeeMapper;
import cn.wyl.system.domain.Menu;
import cn.wyl.user.domain.Logininfo;
import cn.wyl.user.domain.User;
import cn.wyl.user.domain.Wxuser;
import cn.wyl.user.mapper.LogininfoMapper;
import cn.wyl.user.mapper.UserMapper;
import cn.wyl.user.mapper.WxuserMapper;
import cn.wyl.user.service.ILogininfoService;
import cn.wyl.basic.service.impl.BaseServiceImpl;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
//        private String account;
//        private String checkPass;
        //1.空值校验
        if(StringUtils.isEmpty(loginDto.getAccount())||StringUtils.isEmpty(loginDto.getCheckPass())){
            throw new BusinessException("信息不能为空");
        }
        //2.账号校验
        Logininfo logininfo= logininfoMapper.findByAccount(loginDto);
        if (logininfo == null){
            throw new BusinessException("账号或密码错误");
        }
        //3.密码校验
        String inputPwd = Md5Utils.encrypByMd5(loginDto.getCheckPass() + logininfo.getSalt());
        if(!inputPwd.equals(logininfo.getPassword())){
            throw new BusinessException("账号或密码错误");
        }
        //4.用户状态校验-是否禁用
        if(!logininfo.getDisable()){
            throw new BusinessException("该账号被封禁，请联系管理员");
        }
        Map<String, Object> map = loginSuccessJwtHandler(logininfo);
        return map;
    }

    @Override
    public AjaxResult wechatLogin(String code) {
        //1.组装请求地址
        String url = WxConstants.GET_ACK_URL.replace("APPID",WxConstants.APPID)
                .replace("SECRET",WxConstants.SECRET).replace("CODE",code);
        //2.使用HttpUtil工具类发送请求,返回json格式的字符串
        String jsonStr = HttpUtil.httpGet(url);
        //3.将json格式的字符串转成json对象，并获取里面的token和openid
        JSONObject jsonObj = JSONObject.parseObject(jsonStr);
        String accessToken = jsonObj.getString("access_token");
        String openid = jsonObj.getString("openid");
        //4.根据openid去查t_wxuser表
        Wxuser wxuser = wxuserMapper.findByOpenid(openid);
        if(wxuser != null){
            User user = userMapper.findById(wxuser.getUserId());
            if(user != null){
                //免密登录
                Logininfo logininfo = logininfoMapper.findById(user.getLogininfoId());

                Map<String, Object> map = loginSuccessJwtHandler(logininfo);

                return AjaxResult.me().setResultObj(map);

            }
        }
        String params = "?accessToken="+accessToken+"&openid="+openid;
        return AjaxResult.me().setSuccess(false).setResultObj(params);

    }

    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openid = map.get("openid");
        //1.空值校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("输入信息不能为空");
        }
        //2.手机验证码校验
        Object obj = redisTemplate.opsForValue().get("binder:" + phone);
        if(obj == null){
            throw new BusinessException("验证码过期");
        }
        if(!obj.toString().split(":")[0].equals(verifyCode)){
            throw new BusinessException("验证码错误");
        }
        //3.组装第三个请求地址
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN",accessToken).replace("OPENID",openid);
        //4.通过token和openid发送第三个请求，返回json格式字符串
        String jsonStr = HttpUtil.httpGet(url);
        //5.使用fastJson将json格式的字符串转成json对象，再转成一个Wxuser对象【没有user_id】
        Wxuser wxuser = jsonStr2Wxuser(jsonStr);
        //6.先通过openid去找t_wxuser ,如果有直接删除
        Wxuser dbWxuser = wxuserMapper.findByOpenid(openid);
        if(dbWxuser!=null){
            wxuserMapper.delete(dbWxuser.getId());
        }
        //7.想办法创建一个User对象 - 通过phone去创建一个User对象，密码是多少？-随机
        User user = userMapper.findByPhone(phone);
        if(user == null){
            user = phone2User(phone);
            Logininfo logininfo = user2Logininfo(user);

            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            //8.添加User对象 => 生成一个自增id => 将User_id设置到WxUser对象
            userMapper.save(user);
        }
        //9.添加WxUser对象到数据库
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);
        //10.做免密登录
        Logininfo logininfo = logininfoMapper.findById(user.getLogininfoId());

        Map<String, Object> resultMap = loginSuccessJwtHandler(logininfo);

        return AjaxResult.me().setResultObj(resultMap);
    }

    private Map<String,Object> loginSuccessJwtHandler(Logininfo logininfo){
//        //5.使用UUID生成token，将其作为key,并将登录信息保存到redis数据库，设置30分钟有效
//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//        //6.将token和登录信息对象保存到map进行返回
//        Map<String,Object> map = new HashMap<>();
//        map.put("token",token);
//        logininfo.setPassword(null);
//        logininfo.setSalt(null);
//        map.put("logininfo",logininfo);

        //处理密码和盐值
        logininfo.setPassword(null);
        logininfo.setSalt(null);

        Map<String, Object> map = new HashMap<>();
        LoginData loginData = new LoginData();
        map.put("logininfo",logininfo);
        loginData.setLogininfo(logininfo);

        if(logininfo.getType()==0){//0=表示管理员
            //1.获取当前登录人的权限
            List<String> permissions = employeeMapper.getPermissionByLogininfoId(logininfo.getId());
            map.put("permissions",permissions);
            loginData.setPermissions(permissions);
            //2.获取当前登录人菜单
            List<Menu> menus = employeeMapper.getMenusByLogininfoId(logininfo.getId());
            map.put("menus",menus);
            loginData.setMenus(menus);
            //3.将permissions，menus，logininfo封装到LoginData
        }
        try{
            //4.通过工具类获取秘钥
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 300);
            map.put("token",jwtToken);
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String pwd = StrUtils.getComplexRandomString(6);
        String md5Pwd = Md5Utils.encrypByMd5(pwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        JSONObject jsonObj = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(jsonObj.getString("openid"));
        wxuser.setNickname(jsonObj.getString("nickname"));
        wxuser.setHeadimgurl(jsonObj.getString("headimgurl"));
        wxuser.setUnionid(jsonObj.getString("unionid"));
        return wxuser;
    }
}
